import Show from '../model/show.js';
import data from '../model/XdxzData.js';
import puppeteer from '../../../lib/puppeteer/puppeteer.js';
import {
    createAGroupFolder,
    isGroupExist,
    isPlayerExist,
    storagePlayerData,
    getPlayerData,
    Add_beibao_thing,
    Add_星币,
    foundthing,
    exist_beibao_thing,
    getBeibaoData,
    Write_player
} from '../model/function.js';

export class xdxz_chaoshi extends plugin {
    constructor() {
        super({
            name: '[xdxz]小镇超市',
            dsc: '星动小镇超市交互',
            event: 'message',
            priority: 9999999999,
            rule: [
                { 
                    reg: /^#?小镇超市(饮料|食物)?$/,
                    fnc: 'chaoshi'
                },{ 
                    reg: /^#?购买商品((.*)|(.*)*(.*))$/,
                    fnc: 'shopping'
                },{ 
                    reg: /^#?摄入((.*)|(.*)*(.*))$/,
                    fnc: 'sr'
                }
            ]
        })
    }
    async chaoshi(e) {
		//不开放私聊功能
		if (!e.isGroup) {
			return e.reply(['该游戏只能在群内使用']);
		}
		let thing_type = e.msg.replace('#?小镇超市', '');
		let img = await this.supermarket(e, thing_type);
		e.reply(img,true);
		return;
	}
    async shopping(e) {
		//不开放私聊功能
		if (!e.isGroup) {
			return e.reply(['该游戏只能在群内使用']);
		}
        const ID = [e.user_id, e.group_id];
        if (!isPlayerExist(ID[1], ID[0])) {
            e.reply(`买什么买！你来小镇了吗？(请先#加入小镇)`,true);
            return;
        }
        let thing = e.msg.replace('#?', '');
		thing = thing.replace('购买商品', '');
		let code = thing.split('*');
		let thing_name = code[0];
        //默认没有数量
		let quantity = 0;
        if (parseInt(code[1]) != parseInt(code[1])) {
			quantity = 1;
		} else if (parseInt(code[1]) < 1) {
			e.reply(`输入物品数量小于1,现在默认为1`,true);
			quantity = 1;
		}
        else if (parseInt(code[1]) > 10) {
            e.reply(`贪心了不是？一次最多买10！`,true);
            quantity = 10;
        }else {
			quantity = parseInt(code[1]);
		}
        let ifexist = data.cs_list.find((item) => item.name == thing_name);
		if (!ifexist) {
			e.reply(`小镇超市还没有这样的东西:${thing_name}`);
			return;
		}
        let player = await getPlayerData(ID[1], ID[0]);
        let xingbi = player.xingbi;
        //如果没钱，或者为负数
		if (xingbi <= 1) {
			e.reply(`店长：就你这穷酸样，也配来超市？走走走，去找工作赚星币再来！`,true);
			return;
		}
        let commodities_price = ifexist.零售价 * quantity;
		let addWorldmoney = ifexist.零售价 * quantity;
        commodities_price = Math.trunc(commodities_price);
        //计算价格
		if (xingbi < commodities_price) {
			e.reply(
				`抱歉！星币不足以支付${thing_name},还差${commodities_price - xingbi}星币`
			);
			return;
		}
        let Worldmoney = await redis.get('Xdxz:Worldmoney');
        if (
			Worldmoney == null ||
			Worldmoney == undefined ||
			Worldmoney <= 0 ||
			Worldmoney == NaN
		) {
			Worldmoney = 1;
		}
        Worldmoney = Number(Worldmoney);
		Worldmoney = Worldmoney + addWorldmoney;
		Worldmoney = Number(Worldmoney);
		await redis.set('Xdxz:Worldmoney', Worldmoney);
        //符合存入背包
		await Add_beibao_thing(ID[1], ID[0], thing_name, ifexist.class, quantity);
		await Add_星币(ID[1],ID[0],-commodities_price);
        e.reply([
			`购买成功!  获得[${thing_name}]*${quantity},花[${commodities_price}]星币,剩余[${xingbi - commodities_price
			}]星币  `,
			'\n可以在【我的背包】中查看',
		]);
		return;
	}
    async supermarket(e, thing_type) {
        const ID = [e.user_id, e.group_id];
        // 检查群组和玩家是否存在，不存在则创建
        if (!isGroupExist(ID[0])) {
            createAGroupFolder(ID[1]);
        }
        if (!isPlayerExist(ID[1], ID[0])) {
            storagePlayerData(ID[1], ID[0], { 
                xingbi: 250,
                article: [],
                value: 100,
                spouse: '',
                tili:100,
                jingli:100,
                jinengdian: 0,
                jineng: ''
                });
        }
        let cs_list = data.cs_list;
        if (thing_type != '') {
            if (
                thing_type == '饮料' ||
                thing_type == '食物'
            ) {
                cs_list = cs_list.filter((item) => item.class == thing_type);
            }
        }
        let cs_data = {
            user_id: e.user_id,
            cs_list: cs_list,
        };
        const data1 = await new Show(e).get_chaoshiData(cs_data);
        let img = await puppeteer.screenshot('chaoshi', {
            ...data1,
        });
        return img;

    }
    async sr(e){
        // 不开放私聊功能
        if (!e.isGroup) {
            return e.reply(['该游戏只能在群内使用']);
        }

        const ID = [e.user_id, e.group_id];

        // 检查玩家是否存在
        if (!isPlayerExist(ID[1], ID[0])) {
            return e.reply(`达咩！没你这个人存在(请先#加入小镇)`, true);
        }

        // 解析物品和数量
        let thing = e.msg.replace('#?', '').replace('摄入', '');
        let code = thing.split('*');
        let thing_name = code[0];
        //默认没有数量
		let quantity = 0;
        if (parseInt(code[1]) != parseInt(code[1])) {
			quantity = 1;
		} else if (parseInt(code[1]) < 1) {
			e.reply(`输入物品数量小于1,现在默认为1`,true);
			quantity = 1;
		}else {
			quantity = parseInt(code[1]);
		}
        // 检查物品是否存在
        let thing_exist = await foundthing(thing_name);
        if (!thing_exist) {
            return e.reply(`物品${thing_name}不存在！`, true);
        }

        // 检查背包中是否已有该物品
        let x = await exist_beibao_thing(ID[1],ID[0],thing_name, thing_exist.class);
        if (!x) {
            return e.reply(`你的背包里还没有这样的东西:${thing_name}哦！请前往小镇超市购买`, true);
        }
        // 读取并解析背包数据
        try {
            // 获取背包数据文件路径
            const jsonData = await getBeibaoData(ID[1], ID[0]);
            // 查找并计算体力恢复和精力恢复
            const item = await this.findItemInBackpack(jsonData,thing_exist.class,thing_name);
                if (item.name === thing_name) {
                    const jl = item.精力恢复 * quantity;
                    const tl = item.体力恢复 * quantity;
                    // 更新背包物品数量
                    await Add_beibao_thing(ID[1], ID[0], thing_name, thing_exist.class, -quantity);
                    // 解析用户JSON 数据
                    let player = await getPlayerData(ID[1], ID[0]);
                    const jlcha = player.jingli+jl;
                    const tlcha = player.tili+tl;
                    if(jlcha<=101 && tlcha<=101){
                        player.tili+=tl;
                        player.jingli+=jl;
                        await Write_player(ID[1], ID[0], player);
                        // 回复用户
                        return e.reply([
                            `成功摄入[${thing_name}]*${quantity},获得${jl}点精力、${tl}点体力`,
                            '\n可以在【加入小镇】中查看个人面板信息'
                        ]);
                    }else if(jlcha<=101 && tlcha>100){
                        player.jingli+=jl;
                        await Write_player(ID[1], ID[0], player);
                        // 回复用户
                        return e.reply([
                            `成功摄入[${thing_name}]*${quantity},获得${jl}点精力`,
                            '\n可以在【加入小镇】中查看个人面板信息'
                        ]);
                    }else if(jlcha>100 && tlcha<=101){
                        player.tili+=tl;
                        await Write_player(ID[1], ID[0], player);
                        // 回复用户
                        return e.reply([
                            `成功摄入[${thing_name}]*${quantity},获得${jl}点体力`,
                            '\n可以在【加入小镇】中查看个人面板信息'
                        ]);
                    }else{
                        e.reply('体力和精力太多了，再吃就撑了',true);
                        return;
                    };
                }
                return e.reply(`在背包中没有找到名为${thing_name}的物品！`, true);
        } catch (err) {
            return e.reply('处理背包数据时出错，请稍后再试。', true);
        }
    }
    // 根据物品类型选择对应的背包物品数组
    async findItemInBackpack(backpackData, itemType, itemName) {
        const items = backpackData[itemType];
        
        // 遍历数组查找匹配的项目
        for (const item of items) {
            if (item.name === itemName) {
                return item; // 找到匹配的项目，返回它
            }
        }
        
        // 如果没有找到匹配的项目，返回null
        return null;
    }
}